﻿using B.MESUI.Login.A_Public.Constants;
using B.MESUI.Login.A_Public.Helpers;
using B.MESUI.Login.A_Public.仪表台.DTO;
using B.MESUI.Login.BasicData_UI;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.MESUI.Login.A_Public.仪表台
{
    public class DashboardService
    {
        // 生产总量（工单总数）
        public async Task<int> GetProductionTotalAsync()
        {
            try
            {
                string url = HttpClientHelper.GetWorkOrderUrl(ApiEndpoints.WorkOrder.GetWorkOrderList);
                var resp = await HttpClientHelper.GetAsync(url);
                var obj = JObject.Parse(resp);

                // 从 totalCount 字段获取工单总数
                return obj["totalCount"]?.Value<int>() ?? 0;
            }
            catch (Exception ex)
            {
                // 记录错误日志，返回默认值
                System.Diagnostics.Debug.WriteLine($"获取生产总量失败: {ex.Message}");
                return 0;
            }
        }

        // 客户数
        public async Task<int> GetCustomerTotalAsync()
        {
            string url = MethodConst.GetPageCustomer;
            var resp = await BaseMethod.MethodsURL("get", url);
            var obj = JObject.Parse(resp);
            return obj["totalCount"]?.Value<int>() ?? (obj["data"]?.Count() ?? 0);
        }

        // 出入库记录数
        public async Task<int> GetIORecordTotalAsync()
        {
            string url = "http://39.103.49.30:9981/api/IOWareHouse/GetIOWAREHOUSERECORDMODEL"; // 具体接口名请根据实际调整
        //    string fullUrl = HttpClientHelper.GetFullUrl("http://你的仓库API地址", url);
            var resp = await HttpClientHelper.GetAsync(url);
            var obj = JObject.Parse(resp);
            return obj["totalCount"]?.Value<int>() ?? (obj["data"]?.Count() ?? 0);
        }

        // 仓库总数
        public async Task<int> GetWarehouseTotalAsync()
        {
            string url = "http://39.103.49.30:9981/api/WareHouseDefinition/GetWAREHOUSEDEFINITIONMODEL"; // 具体接口名请根据实际调整                                                                                                
            var resp = await HttpClientHelper.GetAsync(url);
            var obj = JObject.Parse(resp);
            return obj["totalCount"]?.Value<int>() ?? (obj["data"]?.Count() ?? 0);
        }


        /// <summary>
        /// 分页获取工单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<(List<WorkOrderDto> List, int TotalCount)> GetWorkOrdersAsync(int pageIndex, int pageSize)
        {
            string url = HttpClientHelper.GetWorkOrderUrl(ApiEndpoints.WorkOrder.GetWorkOrderList)
                + $"?pageIndex={pageIndex}&pageSize={pageSize}";
            var resp = await HttpClientHelper.GetAsync(url);
            var obj = JObject.Parse(resp);

            int totalCount = obj["totalCount"]?.Value<int>() ?? 0;
            var pageDatas = obj["pageDatas"] as JArray;
            var list = new List<WorkOrderDto>();
            if (pageDatas != null)
            {
                foreach (var item in pageDatas)
                {
                    list.Add(new WorkOrderDto
                    {
                        CodeId = item["codeid"]?.ToString(),
                        WorkOrderType = item["workordeR_TYPE"]?.ToString(),
                        ProcessProgress = item["procesS_PROGRESS"]?.ToString(),
                        NumberCol = item["numbeR_COL"]?.Value<int>() ?? 0
                    });
                }
            }
            return (list, totalCount);
        }
        /// <summary>
        /// 分页获取客户列表
        /// </summary>
        public async Task<(List<CustomerDto> List, int TotalCount)> GetCustomerListAsync(int pageIndex, int pageSize)
        {
            string url = MethodConst.GetPageCustomer + $"?pageIndex={pageIndex}&pageSize={pageSize}";
            var resp = await BaseMethod.MethodsURL("get", url);
            var obj = JObject.Parse(resp);

            int totalCount = obj["totalCount"]?.Value<int>() ?? 0;
            var pageDatas = obj["pageDatas"] as JArray;
            var list = new List<CustomerDto>();
            if (pageDatas != null)
            {
                foreach (var item in pageDatas)
                {
                    list.Add(new CustomerDto
                    {
                        customeR_NAME = item["customeR_NAME"]?.ToString(),
                        customeR_NODE = item["customeR_NODE"]?.ToString(),
                        crediT_CODE = item["crediT_CODE"]?.ToString()
                    });
                }
            }
            return (list, totalCount);
        }

        /// <summary>
        /// 工单柱状图
        /// </summary>
        /// <returns></returns>
        public async Task<List<WorkOrderMonthStatDto>> GetWorkOrderMonthStatsAsync()
        {
            string url = "http://39.103.49.30:9983/api/WorkOrder/GetWorkOrderListNumber";
            var resp = await HttpClientHelper.GetAsync(url);
            var obj = JObject.Parse(resp);

            var resultData = obj["resultData"] as JArray;
            var list = new List<WorkOrderMonthStatDto>();
            if (resultData != null)
            {
                foreach (var item in resultData)
                {
                    list.Add(new WorkOrderMonthStatDto
                    {
                        totalNUMBER_COL = item["totalNUMBER_COL"]?.Value<int>() ?? 0,
                        starT_TIME = item["starT_TIME"]?.Value<DateTime>() ?? DateTime.MinValue
                    });
                }
            }
            return list;
        }
    }
}
